package com.mineoj.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mineoj.common.ErrorCode;
import com.mineoj.constant.CommonConstant;
import com.mineoj.exception.BusinessException;
import com.mineoj.exception.ThrowUtils;
import com.mineoj.mapper.CompetitionJoinMapper;
import com.mineoj.model.dto.competition.CompetitionQueryRequest;
import com.mineoj.model.entity.*;
import com.mineoj.model.vo.CompetitionVO;
import com.mineoj.model.vo.UserVO;
import com.mineoj.service.CompetitionService;
import com.mineoj.mapper.CompetitionMapper;
import com.mineoj.service.UserService;
import com.mineoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 明月
* @description 针对表【competition(比赛)】的数据库操作Service实现
* @createDate 2025-04-20 18:59:17
*/
@Service
public class CompetitionServiceImpl extends ServiceImpl<CompetitionMapper, Competition>
    implements CompetitionService{
    @Resource
    private UserService userService;

    @Resource
    private CompetitionMapper competitionMapper;

    @Resource
    private CompetitionJoinMapper competitionJoinMapper;
    

    @Override
    public void validCompetition(Competition competition, boolean add) {
        if (competition == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = competition.getTitle();
        String content = competition.getContent();
        Date beginTime = competition.getBeginTime();
        Date endTime = competition.getEndTime();
        
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(beginTime == null || endTime == null, ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param competitionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Competition> getQueryWrapper(CompetitionQueryRequest competitionQueryRequest) {
        QueryWrapper<Competition> queryWrapper = new QueryWrapper<>();
        if (competitionQueryRequest == null) {
            return queryWrapper;
        }
        String searchText = competitionQueryRequest.getSearchText();
        String sortField = competitionQueryRequest.getSortField();
        String sortOrder = competitionQueryRequest.getSortOrder();
        Long id = competitionQueryRequest.getId();
        String title = competitionQueryRequest.getTitle();
        String content = competitionQueryRequest.getContent();
        Date beginTime = competitionQueryRequest.getBeginTime();
        // 拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        // 开始时间之前的
        queryWrapper.le(ObjectUtils.isNotEmpty(beginTime), "beginTime", beginTime);
        
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public CompetitionVO getCompetitionVO(Competition competition, HttpServletRequest request) {
        CompetitionVO competitionVO = CompetitionVO.objToVo(competition);
        long competitionId = competition.getId();
        // 1. 关联查询用户信息
        Long userId = competition.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        competitionVO.setUser(userVO);
        // 2. 已登录，获取用户参加状态
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            // 获取参加
            QueryWrapper<CompetitionJoin> competitionJoinQueryWrapper = new QueryWrapper<>();
            competitionJoinQueryWrapper.in("competitionId", competitionId);
            competitionJoinQueryWrapper.eq("userId", loginUser.getId());
            CompetitionJoin competitionJoin = competitionJoinMapper.selectOne(competitionJoinQueryWrapper);
            competitionVO.setHasJoin(competitionJoin != null);

        }
        return competitionVO;
    }

    @Override
    public Page<CompetitionVO> getCompetitionVOPage(Page<Competition> competitionPage, HttpServletRequest request) {
        List<Competition> competitionList = competitionPage.getRecords();
        Page<CompetitionVO> competitionVOPage = new Page<>(competitionPage.getCurrent(), competitionPage.getSize(), competitionPage.getTotal());
        if (CollUtil.isEmpty(competitionList)) {
            return competitionVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = competitionList.stream().map(Competition::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 已登录，获取用户参加状态
        Map<Long, Boolean> competitionIdHasJoinMap = new HashMap<>();

        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            Set<Long> competitionIdSet = competitionList.stream().map(Competition::getId).collect(Collectors.toSet());
            loginUser = userService.getLoginUser(request);
            // 获取参加
            QueryWrapper<CompetitionJoin> competitionJoinQueryWrapper = new QueryWrapper<>();
            competitionJoinQueryWrapper.in("competitionId", competitionIdSet);
            competitionJoinQueryWrapper.eq("userId", loginUser.getId());
            List<CompetitionJoin> competitionCompetitionJoinList = competitionJoinMapper.selectList(competitionJoinQueryWrapper);
            competitionCompetitionJoinList.forEach(competitionCompetitionJoin -> competitionIdHasJoinMap.put(competitionCompetitionJoin.getCompetitionId(), true));
        }
        // 填充信息
        List<CompetitionVO> competitionVOList = competitionList.stream().map(competition -> {
            CompetitionVO competitionVO = CompetitionVO.objToVo(competition);
            Long userId = competition.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            competitionVO.setUser(userService.getUserVO(user));
            competitionVO.setHasJoin(competitionIdHasJoinMap.getOrDefault(competition.getId(), false));
            return competitionVO;
        }).collect(Collectors.toList());
        competitionVOPage.setRecords(competitionVOList);
        return competitionVOPage;
    }


}




